package org.unicen.exa.io.worker.assigner.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.unicen.exa.io.worker.assigner.core.model.JobWorking;
import org.unicen.exa.io.worker.assigner.dao.JobWorkingDao;


@Repository("jobWorkingDao")
public class JobWorkingDaoImpl extends BaseDaoImpl<JobWorking> implements JobWorkingDao<JobWorking> {

	private Logger logger = Logger.getLogger(JobWorkingDaoImpl.class);

	private Map<Long, JobWorking> map = new HashMap<Long, JobWorking>();
	

	public void post(Long id, JobWorking model) {
//		logger.info(String.format("STORING job with id equal to %s", id.toString()));
		map.put(id, model);
	}

	public void put(JobWorking model) {
//		logger.info(String.format("MERGING job with id equal to %s", model.getId().toString()));
		map.put(model.getId(), model);
		
		
	}

	public void delete(JobWorking model) {
//		logger.info(String.format("REMOVING job with id equal to %s", model.getId().toString()));
		map.remove(model.getId());
	}

	public JobWorking get(Long id) {
//		logger.info(String.format("GETTING job with id equal to %s", id.toString()));
		return map.get(id);
	}

	public synchronized List<JobWorking> gets() {
//		logger.info(String.format("GETTING all jobs"));
		List<JobWorking> list = new ArrayList<JobWorking>();
		for (Entry<Long, JobWorking> iterable_element : map.entrySet()) {
			list.add(iterable_element.getValue());
		}
		
		return list;
	}

	public synchronized List<JobWorking> findByWorkerIdAndStatePending(Long id, String jobStatePending) {
		logger.info(String.format("FINDING jobs in runtime where workerId=%s and state=%s",id,jobStatePending));
		List<JobWorking> list = new ArrayList<JobWorking>();
		for (Entry<Long, JobWorking> iterable_element : map.entrySet()) {
			if (iterable_element.getValue().getWorkerId().equals(id) && iterable_element.getValue().getStatus().equals(jobStatePending)){
				list.add(iterable_element.getValue());
			}
		}
		return list;
	}

}
